package com.ruge.test.Utils;

import cn.hutool.core.util.NetUtil;
import org.junit.Test;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 爱丽丝、如歌  创建于 2018/8/14 16:20
 * 说明:
 */
public class NetUtils {
	@Test
	public void   test1(){
		String ipv4 = this.getIPV4();
		System.out.println(ipv4);
	}
	public String getIPV4(){
		Enumeration allNetInterfaces = null;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (java.net.SocketException e) {
			e.printStackTrace();
		}
		InetAddress ip = null;
		while (allNetInterfaces.hasMoreElements())
		{
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
					.nextElement();
			Enumeration addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements())
			{
				ip = (InetAddress) addresses.nextElement();
				if (ip != null && ip instanceof Inet4Address)
				{
					if(ip.getHostAddress().equals("127.0.0.1")){
						continue;
					}
					return ip.getHostAddress();
				}
			}
		}
		return "网络无连接！";
	}

}
